import React, {useEffect, useRef} from 'react';
import {useNavigate} from "react-router-dom";

const FrameLayout: React.FC<any> = ({path, ...props}: any) => {
  const timerRef = useRef();
  const navigate = useNavigate();
  const elementResize = (
    {
      element,
      width = 1920,
      height = 972,
      type = 'padding'
    }
  ) => {
    const parentDom = element.parentElement;
    // parentDom.style.width = '100%'
    // parentDom.style.height = '100%'
    const offsetWidth = parentDom.clientWidth;
    const offsetHeight = parentDom.clientHeight;
    let top = 0;
    let left = 0;
    let scaleX = (offsetWidth / width).toFixed(6);
    let scaleY = (offsetHeight / height).toFixed(6);
    if (type === 'padding') {
      if (scaleX < scaleY) {
        scaleY = scaleX;
        top = (offsetHeight - height * scaleX) / 2;
      } else if (scaleX > scaleY) {
        scaleX = scaleY;
        left = (offsetWidth - width * scaleX) / 2;
      } else {
        // 同步放大/缩小
      }
    } else if (type === 'width') {
      scaleY = scaleX;
    } else if (type === 'height') {
      scaleX = scaleY;
    } else if (type === 'full') {
      // do nothing
    }

    element.style.width = `${width}px`;
    element.style.height = `${height}px`;
    // element.style.marginLeft = `${left}px`
    // element.style.marginTop = `${top}px`
    element.style.webkitTransformOrigin = 'left top 0px';
    element.style.MozTransformOrigin = 'left top 0px';
    element.style.transformOrigin = 'left top 0px';
    element.style.webkitTransform = `translate(${left}px, ${top}px) scale(${scaleX}, ${scaleY})`;
    element.style.MozTransform = `translate(${left}px, ${top}px) scale(${scaleX}, ${scaleY})`;
    element.style.transform = `translate(${left}px, ${top}px) scale(${scaleX}, ${scaleY})`;
  }

  const bodyResize = (width = 1920, height = 972, type = 'padding') => {
    elementResize({
      element: document.body,
      width,
      height,
      type
    });
  }
  useEffect(() => {
    window.addEventListener('resize', () => {
      clearTimeout(timerRef.current);
      timerRef.current = setTimeout(() => {
        bodyResize(1920, 972);
      }, 200);
    });
    window.addEventListener("message", (event) => {
      const data = event.data || {}
      if (data.type === 'toPage') {
        navigate(data.link)
      }
    }, false);
    bodyResize(1920, 972);
  }, [])

  return (
    <>
    {console.log('path',path)}
      <iframe id="app-iframe" src={`${path}`} style={{width: '100%', height: '100vh'}} frameBorder="0"
              scrolling="no">

      </iframe>
    </>
  );
};

export default FrameLayout;
